package com.hnyfkj.jyindustry.common.oauth2;

import com.hnyfkj.jyindustry.common.exception.HnyfkjBusinessException;

import java.security.MessageDigest;
import java.util.UUID;

/**
 * @program: jyindustry
 * @description:oauth2 token生成类
 * @author: zl
 * @create: 2020-07-09 18:05
 **/
public class TokenGenerator {

	public static String generateValue() {
		return generateValue(UUID.randomUUID().toString());
	}

	private static final char[] HEXCODE = "0123456789abcdef".toCharArray();

	public static String toHexString(final byte[] data) {
		if (data == null) {
			return null;
		}
		final StringBuilder r = new StringBuilder(data.length * 2);
		for (final byte b : data) {
			r.append(HEXCODE[(b >> 4) & 0xF]);
			r.append(HEXCODE[(b & 0xF)]);
		}
		return r.toString();
	}

	public static String generateValue(final String param) {
		try {
			final MessageDigest algorithm = MessageDigest.getInstance("MD5");
			algorithm.reset();
			algorithm.update(param.getBytes());
			final byte[] messageDigest = algorithm.digest();
			return toHexString(messageDigest);
		} catch (final Exception e) {
			throw new HnyfkjBusinessException("生成Token失败", e);
		}
	}
}
